package  
{
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.events.MouseEvent;
  import mge.graph.Edge;
	/**
   * ...
   * @author ivan
   */
  public class EdgeTool extends Sprite
  {
    
    public function EdgeTool(graphStage:GraphStage) 
    {
      this.graphStage = graphStage;
      
      mouseEnabled = false;
      addEventListener(Event.ENTER_FRAME, onEnterFrame);
      
      addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
    }
    
    private function onAddedToStage(e:Event):void
    {
      removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
      
      parent.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
      parent.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
      parent.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
    }
    
    private function onMouseDown(e:MouseEvent):void
    {
      if (!enabled) return;
      var vn:VisualNode = e.target as VisualNode;
      if (vn)
        source = vn;
    }
    
    private function onMouseUp(e:MouseEvent):void
    {
      var vn:VisualNode = e.target as VisualNode;
      if (vn)
        target = vn;
        
      if (source && target)
      {
        graphStage.addEdge(new Edge(source.node, target.node));
      }
      source = target = null;
    }
    
    private function onMouseMove(e:MouseEvent):void
    {
      
    }
    
    private function onEnterFrame(e:Event):void
    {
      graphics.clear();
      graphics.lineStyle(1);
      graphics.beginFill(0x000000, 0.5);
      
      if (source && !target)
      {
        graphics.moveTo(source.node.x, source.node.y);
        graphics.lineTo(mouseX, mouseY);
      }
      
      for (var i:int = 0; i < graphStage.numChildren; i++)
      {
        var ve:VisualEdge = graphStage.getChildAt(i) as VisualEdge;
        if (ve)
        {
          graphics.moveTo(ve.edge.source.x, ve.edge.source.y);
          graphics.lineTo(ve.edge.target.x, ve.edge.target.y);
        }
      }
      graphics.endFill();
    }
    
    public var enabled:Boolean;
    
    private var graphStage:GraphStage;
    private var source:VisualNode;
    private var target:VisualNode;
  }

}